/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filter;

import entity.Users;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author owtee
 */
public class FilterSessionTimeout implements Filter {

    public FilterSessionTimeout() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String url = req.getServletPath();

        Users member = (Users) session.getAttribute("member");

        // Check first index page don't check
        boolean chkLogon = url.endsWith("Logon");   
        boolean chkIndex = url.endsWith("index.jsp");   

        // if session doesn't exist, forward user to welcome page
        if (member == null) {
            if(chkIndex == true) {
                RequestDispatcher rd = request.getRequestDispatcher("../view/index.jsp");
                rd.forward(request, response);
                return;
            } else if (chkLogon == false) {
                request.setAttribute("sessionTimeOut", "timeout");
                RequestDispatcher rd = request.getRequestDispatcher("../view/index.jsp");
                rd.forward(request, response);
                return;
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}
